<?php

namespace addons\shopro\job;

use addons\shopro\model\Activity;
use addons\shopro\model\RobOrderModel;
use think\queue\Job;

/**
 * 抢购自动分配名额
 */
class ActivityRobOrder extends BaseJob
{

    /**
     * 抢购自动分配名额
     */
    public function autoRob(Job $job, $data)
    {
        try {
            $activity = $data['activity'];
            $activity = Activity::get($activity['id']);

            if ($activity) {
                // 获取预约列表
                $orderUserId = RobOrderModel::where(['activity_id' => $activity->id, 'is_rob' => 2])
                    ->field('user_id')
                    ->select();

                if (!empty($orderUserId)) {
                    // 已提前设置资格人数
                    $count = RobOrderModel::where(['activity_id' => $activity->id, 'is_rob' => 1])
                        ->count();
                    // 剩余名额
                    $num = $activity->num - $count;

                    if (!empty($num)) {
                        $arr         = [];
                        $orderUserId = array_column(collection($orderUserId)->toArray(), 'user_id');

                        if (count($orderUserId) <= $num) {
                            $arr = $orderUserId;
                        } else {
                            // 随机取值
                            $arr = randomSelectArr($orderUserId, $num);
                        }

                        // 分配资格
                        foreach ($arr as $userId) {
                            RobOrderModel::where(['user_id' => $userId, 'activity_id' => $activity->id])->update([
                                'is_rob' => 1
                            ]);
                        }
                    }
                }
            }

            // 删除 job
            $job->delete();
        } catch (\Exception $e) {
            // 队列执行失败
            \think\Log::write('queue-' . get_class() . '-autoClose' . '：执行失败，错误信息：' . $e->getMessage());
        }
    }

}